package com.ykdl.member.kid.marketcard;

import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.pay.PayResult;
import com.google.gson.JsonObject;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.fittool.BaseActivity;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.gears.WelcomeActivity;

public class PaySelectActivity extends BaseScreen{

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	private static final int GET_PAY_INFO = 3;

	private static final int GET_WX_PAY_INFO = 4;

	private String orderNumber;

	ProgressDialog pd;

	PayReq req;
	
	public static PaySelectActivity  paySelectActivity;
	

	final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();
				Log.d("dure", "resultStatus = " + resultStatus);

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(PaySelectActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(PaySelectActivity.this,
							PaySuccessActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(intent);
					finish();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PaySelectActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PaySelectActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(PaySelectActivity.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			case GET_PAY_INFO: {
				pd.dismiss();
				excutePay((String) msg.obj);
				break;
			}
			case GET_WX_PAY_INFO:
				pd.dismiss();
				genPayReq((String) msg.obj);
				sendPayReq();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		paySelectActivity = this;

		orderNumber = this.getIntent().getStringExtra(KidAction.ORDER_ID);
		setTopTitle("选择支付方式", 0, R.drawable.back_bg, new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PaySelectActivity.this,
						MyOrderActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				finish();
			}
		}, 0, 0, null, R.drawable.title_bg, false);
		setContent(R.layout.activity_pay_select);
		// 支付宝支付
				findViewById(R.id.rl_alipay).setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO 支付宝支付
						pd = ProgressDialog.show(PaySelectActivity.this, "",
								"正在获取支付信息...", true, true);
						pay(KidConfig.BASE_CARD_SERVER + "/api/v1/alipay_make_payment_info/",
								GET_PAY_INFO);
					}
				});
				// 微信支付
				findViewById(R.id.rl_weixin).setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO 微信支付
						req = new PayReq();
						// GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
						// getPrepayId.execute();
						pd = ProgressDialog.show(PaySelectActivity.this, "",
								"正在获取支付信息...", true, true);
						pay(KidConfig.BASE_CARD_SERVER + "/api/v1/wxpay_make_payment_info/",
								GET_WX_PAY_INFO);
					}
				});
	}

	/**
	 * 获取支付订单信息
	 * 
	 */
	public void pay(final String url, final int type) {

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				requestByHttpGet(url, type);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	private void excutePay(final String payInfo) {

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(PaySelectActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	// HttpGet方式请求
	public void requestByHttpGet(String url, int type) {
		// 新建HttpGet对象
		HttpGet httpGet = new HttpGet(url + orderNumber);
		// 获取HttpClient对象
		HttpClient httpClient = new DefaultHttpClient();
		// 获取HttpResponse实例
		HttpResponse httpResp = null;
		Log.d("dure", "url = " + (url + orderNumber));
		try {
			httpResp = httpClient.execute(httpGet);
			Log.i("dure", "httpResp.getStatusLine().getStatusCode() = "
					+ httpResp.getStatusLine().getStatusCode());
			// 判断是够请求成功
			if (httpResp.getStatusLine().getStatusCode() == 200) {
				// 获取返回的数据
				String result = EntityUtils.toString(httpResp.getEntity(),
						"UTF-8");
				Log.i("dure", "HttpGet方式请求成功，返回数据如下：");
				Message msg = new Message();
				msg.what = type;
				JSONObject jsonObject = new JSONObject(result);
				msg.obj = jsonObject.getString("res");
				Log.i("dure", jsonObject.getString("res") + "");
				mHandler.sendMessage(msg);
			} else {
				Log.i("dure", "HttpGet方式请求失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		// super.onBackPressed();
		Intent intent = new Intent(PaySelectActivity.this,
				MyOrderActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(intent);
		finish();
	}

	private void genPayReq(String res) {

		try {
			JSONObject resObject = new JSONObject(res);
			req.appId = resObject.getString("appid");
			req.partnerId = resObject.getString("partnerid");
			req.prepayId = resObject.getString("prepayid");
			req.packageValue = "Sign=WXPay";
			req.nonceStr = resObject.getString("noncestr");
			req.timeStamp = resObject.getString("timestamp");
			req.sign = resObject.getString("sign");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void sendPayReq() {

		Log.d("dure", "req = " + req.toString());
		msgApi.registerApp(req.appId);
		msgApi.sendReq(req);
	}

}
